//
//  WCNMeSettingVC.m
//  WCN
//
//  Created by 杨鑫 on 15/6/2.
//  Copyright (c) 2015年 ShanghaiCize Trade And Business Co., Ltd. All rights reserved.
//

#import "WCNMeSettingVC.h"
#import "WCNMulTextEditVC.h"

//
#import "WCNMulTextTCell.h"
#import "WCNSwitchTCell.h"
#import "WCButton.h"
#import "WCInfoEditView.h"
#import "WCPickerView.h"
#import "WCNVariableCell.h"
//
#import "UILabel+Utilities.h"
#import "UINavigationItem+Offset.h"
#import "NSString+Utilities.h"
#import "NSObject+Utilities.h"
//
#import "WCPopupLayerManager.h"
#import "WCDefaultManager.h"
#import "WCCoreDataStore.h"
#import "WCNetworkAccessManager.h"
//
#import "Constants.h"
#import "WeekDayModel.h"
#import "WCNMeSetTimes(replace)VC.h"
#import "WCNServiceConfigModel.h"
#import "Macros.h"

static NSString *cellId = @"WCNMulTextTCell";
static NSString *switchId = @"WCNSwitchTCell";
static NSArray *serviceRadiuses;




@interface WCNMeSettingVC ()
{
    WCNVariableCell *_cell;
    NSString *_nurseId;

}
@property (nonatomic, strong) WCNMulTextTCell *prototypeCell;

@property (nonatomic, strong) WCNServiceConfigModel *service;
@property (nonatomic, strong) NSString *url;

@property (nonatomic) BOOL vcload;

@end

@implementation WCNMeSettingVC



- (instancetype)init
{
    
    self = [super initWithStyle:UITableViewStyleGrouped];
    if (self) {
//        self.title = @"服务设置";
        
        _nurseId = [[WCDefaultManager shareMg] account].stringId;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self configNavItem];
  
   
}

- (void)configNavItem
{
    
    
        
    // Do any additional setup after loading the view.
    WCButton *rightBtn = [WCButton wcButtonWithType:WCButtonTypeSave];
    [rightBtn addTarget:self action:@selector(save) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationItem addRightBarButtonItem:rightBtn];
    
    self.view.backgroundColor = kAppBg;
    
    [self.tableView registerNib:[UINib nibWithNibName:cellId bundle:nil] forCellReuseIdentifier:cellId];
    [self.tableView registerNib:[UINib nibWithNibName:switchId bundle:nil] forCellReuseIdentifier:switchId];
    [self.tableView registerNib:[UINib nibWithNibName:@"WCNVariableCell" bundle:nil] forCellReuseIdentifier:@"notCellId"];
    


}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
//    

}

- (void)save
{

    
    MBProgressHUD *hud = [[WCPopupLayerManager shareMg] showSimple:self.navigationController.view];


//    self.config.price
    NSMutableDictionary *muParams =[NSMutableDictionary dictionary];
    muParams[@"nursingType"] =self.config.serviceType;
    muParams[@"price"] =[NSNumber numberWithDouble:[self.config.price doubleValue]];
    
    if ([self.config.isEnabled isEqualToString:@"YES"]) {
        muParams[@"isEnabled"] =@"YES";
    }else{
        muParams[@"isEnabled"] =@"NO";
    }
    
//    muParams[@"serviceRadius"] =@([self.config.serviceRadius NSInteger]);
    muParams[@"serviceNote"] =self.config.serviceNote;
    weakSelf_define;
    NSString *url =[NSString stringWithFormat:@"%@%@%@",kUpdateSeviceConfig_part,_nurseId,@"/updateService"];
    //参数是 json数据
    [[WCNetworkAccessManager sharedMg] POST:url parameters:muParams success:^(NSDictionary *result){
        NSLog(@"%@",result);
        [[WCPopupLayerManager shareMg] showTextOnly:result[@"data"] withView:weakSelf.view];
        [[WCCoreDataStore shareStore] updateAccountService:muParams];
        [self performBlock:^{
            [self.navigationController popViewControllerAnimated:YES];
        } afterDelay:.3];
    } failure:^(NSString *msg){
        [[WCPopupLayerManager shareMg] showTextOnly:msg withView:weakSelf.view];
        
          } netError:nil always:^{
        [hud hide:YES];
    }];
}

#pragma mark - <UITableViewDelegate, UITableViewDataSource>

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0 ) {
        return 2;
    } else if (section == 1) {
        return 1;
    }
    
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat h =44;
    if (_cell) {
      h = [_cell  cellHeight];
        _cell =nil;
    }

    
    return h;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//     AccountServiceConfigEntity *config = self.service.serviceConfigs[0];
    if (indexPath.section == 0 && indexPath.row == 1) {
        WCNSwitchTCell *cell = [tableView dequeueReusableCellWithIdentifier:switchId forIndexPath:indexPath];
       
        cell.switchTitle.text = @"服务开关";
        cell.wcSwitch.on = [self.config.isEnabled boolValue];
        cell.switchChange = ^(BOOL isOn){
            NSString *isEnable =@"NO";
            if (isOn) isEnable =@"YES";
            _config.isEnabled = isEnable;
        };
        return cell;
    } else if (indexPath.section !=1){
        WCNMulTextTCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexPath];
        cell.mulText.textAlignment = NSTextAlignmentRight;
        cell.mulText.textColor = HexRGB(0x61606e);
        cell.mulText.numberOfLines = 1;
        
        if (indexPath.section == 0) {
            if (indexPath.row == 0) {
              
                
                cell.textTitle.text = @"服务单价";
                cell.mulText.text = [NSString stringWithFormat:@"%.2f元", [self.config.price doubleValue]];
            }
        }
//        else if (indexPath.section == 1) {
//            if (indexPath.row == 0) {
//                cell.textTitle.text = @"服务半径";
////                cell.mulText.text = [NSString radiusToChString:self.service.serviceRadius];
//                cell.mulText.text =@"暂无";
//            } else if (indexPath.row == 1) {
//                cell.textTitle.text = @"服务商圈";
//                cell.mulText.numberOfLines = 0;
//                cell.mulText.text = self.service.serviceArea;
//                [cell.mulText showAttributedText:0 lineSpace:5];
//            }
//         else if (indexPath.section == 2) {
//            cell.textTitle.text = @"时间设置";
//            cell.mulText.textColor = HexRGB(0xc7c8cc);
//            cell.mulText.text = @"服务可预约时间设置";
//         }
//         
        
        
        return cell;
    }else{
        WCNVariableCell *cell =[tableView dequeueReusableCellWithIdentifier:@"notCellId" forIndexPath:indexPath];
//        AccountServiceConfigEntity *config =self.service.serviceConfigs[0];
        _cell = cell;
        [cell configWith:[NSString stringWithFormat:@"服务说明:\n%@",self.config.serviceNote]];
        return cell;
     
    }
   
    
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 15;
    }
    
    return 15-kOnePX;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 2) {
        return 60;
    }
    
    return kOnePX;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 2) {
        UILabel *label = [[UILabel alloc] init];
        label.translatesAutoresizingMaskIntoConstraints = NO;
        label.text = @"注: 可预约时间按周设置(默认自动重复), 患者端默认可预约未来一周时间!";
        label.textColor = HexRGB(0xb2b3b5);
        label.font = [UIFont systemFontOfSize:13.0];
        label.numberOfLines = 0;
        [label showAttributedText:0 lineSpace:6];
        
        UIView *footer = [[UIView alloc] init];
        
        [footer addSubview:label];
        [footer addConstraint:[NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeTop
                                                           relatedBy:NSLayoutRelationEqual
                                                              toItem:footer attribute:NSLayoutAttributeTop
                                                          multiplier:1 constant:10]];
        [footer addConstraint:[NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeLeading
                                                           relatedBy:NSLayoutRelationEqual
                                                              toItem:footer attribute:NSLayoutAttributeLeading
                                                          multiplier:1 constant:10]];
        [footer addConstraint:[NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeTrailing
                                                           relatedBy:NSLayoutRelationEqual
                                                              toItem:footer attribute:NSLayoutAttributeTrailing
                                                          multiplier:1 constant:-10]];
        
        return footer;
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
//            AccountServiceConfigEntity *config = self.service.serviceConfigs[0];
            
            WCInfoEditView *editView = [[WCInfoEditView alloc] init];
            editView.type = WCInfoEditTypeMoney;
            editView.titleLabel.text = @"服务定价";
//            editView.limitLenth =8;
            editView.textField.keyboardType = UIKeyboardTypeDecimalPad;
            editView.save = ^(NSString *txt){
                self.config.price = txt;

                  [tableView reloadData];
                return YES;
            };
            [editView showIn:self.navigationController.view animated:YES];
        }
    }
//        else if (indexPath.section == 1) {
//        if (indexPath.row == 0) {
        
            
            
//            int index = self.service.serviceRadius/1000-1;
//            if (index > 5) index = 4;
//            if (index < 0) index = 0;
            
//            WCPickerView *picker = [[WCPickerView alloc] init];
//            picker.titleLabel.text = @"服务半径";
//            picker.pickerDataSource = serviceRadiuses;
//            [picker.picker selectRow:index inComponent:0 animated:YES];
//            picker.close = ^(NSInteger selected){
//                self.service.serviceRadius = (int)selected*1000+1000;
//                [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
//            };
//            [picker show:self.navigationController completion:nil];
//        }
//        else if (indexPath.row == 1) {
//            WCNMulTextEditVC *vc = [[WCNMulTextEditVC alloc] initWithType:WCNMulTextEditSave];
//            vc.title = @"服务商圈";
//            vc.textViewPlaceholder = @"请填写服务商圈";
//            vc.textViewValue = self.service.serviceArea;
//            vc.canEmpty = YES;
//            vc.callback = ^(NSString *text){
//                self.service.serviceArea = text;
//                [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
//            };
//            [self.navigationController pushViewController:vc animated:YES];
//        }
//    }
    else if (indexPath.section == 1) {
        weakSelf_define;
        WCNMulTextEditVC *vc = [[WCNMulTextEditVC alloc] initWithType:WCNMulTextEditSave];
        vc.title = @"服务说明";
        vc.textViewPlaceholder = @"服务说明";
//        vc.textViewValue = self.service.serviceArea;
        vc.canEmpty = YES;
        vc.callback = ^(NSString *text){
            self.config.serviceNote = text;
            [weakSelf.tableView reloadData];
        };
        [self.navigationController pushViewController:vc animated:YES];
    }

//    else if (indexPath.section == 2) {
//        MBProgressHUD *hud = [[WCPopupLayerManager shareMg] showSimple:self.navigationController.view];
//     
//        NSDictionary *unUsedParams =@{@"nurseId":_nurseId};
//        NSDictionary *usedParams =@{@"nurseId":_nurseId,@"nursingType":self.config.serviceType};
//
//        __weak typeof(self) weakSelf =self;
//        [[WCNetworkAccessManager sharedMg] POST:kSerViceTime_nnused parameters:unUsedParams success:^(NSDictionary *result){
//           
//            // 第二次 获取设置过的服务
//            NSMutableArray *dataArr =[weakSelf signSelectd:NO withDataArray:result[@"data"]];
//            [[WCNetworkAccessManager sharedMg] POST:kServiceTime_used  parameters:usedParams success:^(NSDictionary *responseObject) {
//                [dataArr addObjectsFromArray:[weakSelf signSelectd:YES withDataArray:responseObject[@"data"]]];
//                
//                WCNMeSetTimes_replace_VC *vc =[[WCNMeSetTimes_replace_VC alloc]init];
//                vc.callBack = ^(NSString *jsonStr){
//                    [weakSelf updateTimeDataWith:jsonStr];
//                };
//                vc.dataArray =dataArr;
//                [weakSelf.navigationController pushViewController:vc animated:YES];
//                
//            } failure:nil netError:nil always:^{
//                [hud hide:YES];
//            }];
//            
//            
//            
//        } failure:nil netError:nil always:^{
//            
//        }];
//        
//        
//        
//    }
}
//- (void)updateTimeDataWith:(NSString *)jsonStr
//{
//    __weak typeof(self) weakSelf =self;
//    NSMutableDictionary *params =[NSMutableDictionary dictionary];
//    params[@"nurseId"] = _nurseId;
//    params[@"nursingType"] =self.config.serviceType;
//    params[@"timeSettings"] =jsonStr;
//     [[WCNetworkAccessManager sharedMg]POST:kUpdateTimeData parameters:params success:^(NSDictionary *responseObject) {
//          [[WCPopupLayerManager shareMg] showTextOnly:responseObject[@"data"] withView:weakSelf.view];
//             } failure:^(NSString *msg) {
//                
//
//         
//     } netError:nil always:^{
//         
//     }];
//   
//}
//- (NSMutableArray *)signSelectd:(BOOL)isSign withDataArray:(NSArray *)dataArray
//{
//    NSMutableArray *signArray =[NSMutableArray array];
//    for (NSDictionary *timeDict in dataArray) {
//        timePeroidModel *model =[[timePeroidModel alloc]init];
//        [model setValuesForKeysWithDictionary:timeDict];
//        if (isSign) {
//            model.isSelectdItem = YES;
//        }else{
//            model.isSelectdItem =NO;
//        }
//        [signArray addObject:model];
//    }
//    return signArray;
//
//}
@end
